package com.crazypos.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crazypos.common.ApiRestResponse;
import com.crazypos.common.utils.SecurityUtil;
import com.crazypos.constant.UserTypeConstant;
import com.crazypos.pojo.UserEntity;
import com.crazypos.pojo.bo.AdminCreateUserBO;
import com.crazypos.pojo.bo.AdminUpdateOwnerBO;
import com.crazypos.pojo.bo.GetUserListBO;
import com.crazypos.security.entity.UserDetailEntity;
import com.crazypos.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUserService userService;

    @PostMapping("/create")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiRestResponse createOwner(@RequestBody @Validated AdminCreateUserBO createUserBO) {
        UserDetailEntity loginUser = SecurityUtil.getUserInfo();
        String currentId = SecurityUtil.getUserId();
        String createUserType = UserTypeConstant.EMPLOYEE;
        if(loginUser.getType() == UserTypeConstant.ADMIN){
            // 超级管理员创建 OWNER
            createUserType = UserTypeConstant.OWNER;
        }
        userService.adminCreateUser(createUserBO, createUserType, currentId);
        return ApiRestResponse.success();
    }

    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN') or hasPermission('/users/list','SYS:QUERY_USER')")
    public ApiRestResponse getOwnerList(@Validated GetUserListBO bo) {
        UserDetailEntity loginUser = SecurityUtil.getUserInfo();
        String createUserType = UserTypeConstant.EMPLOYEE;
        if(loginUser.getType() == UserTypeConstant.ADMIN){
            // 超级管理员创建 OWNER
            createUserType = UserTypeConstant.OWNER;
        }
        IPage<UserEntity> result = userService.getUserList(bo, createUserType);
        return ApiRestResponse.success(result);
    }

    @PostMapping("/update")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiRestResponse updateUser(@RequestBody @Validated AdminUpdateOwnerBO bo) {
        userService.adminUpdateOwner(bo);
        return ApiRestResponse.success();
    }
}
